﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Net;
using System.Web;
using System.IO;
using System.Text;


public class BaiduAIFaceMgr : MonoBehaviour {
	
	private string app_id= "10785208";
	private string api_key = "xXUxPXui8ACW2QGtuLbjafGv";
	private string secret_key = "IuGxSbuV7Bitysm2XXLPld2IMxSX3ZuD";		
	//we get this following  token  since  2018 02 05.    last for 30 days
	//24.e10414da96e27a71c7dd0ee92eb064ac.2592000.1520400580.282335-10785208
	public string token="24.e10414da96e27a71c7dd0ee92eb064ac.2592000.1520400580.282335-10785208";
	private string token_url = "https://aip.baidubce.com/oauth/2.0/token?";
	public  string Tokenresult=string.Empty;


	//https://aip.baidubce.com/rest/2.0/face/v2/detect?access_token=24.f9ba9c5341b67688ab5added8bc91dec.2592000.1485570332.282335-8574074
	public bool enableMarkDetedted=true;
	private string BaiduAI_Face_url_detect   = "https://aip.baidubce.com/rest/2.0/face/v1/detect?";   //v1  Maybe  v2 
	public string BaiduFaceStr=string.Empty;

	//For getting the identification among the users in a userGroup. Usually we take the return user with the highest score and the score bigger than 80 as the requested user.
	public bool enableIdentify=true;
	private string BaiduAI_Face_url_identify = "https://aip.baidubce.com/rest/2.0/face/v2/identify";
	public string BaiduFaceIdentifyStr=string.Empty;

	//Add user image and user ID;
	public bool enableAddID=true;
	private string BaiduAI_Face_url_AddUserID= "https://aip.baidubce.com/rest/2.0/face/v2/faceset/user/add";
	public  string UserIDResult=string.Empty;


	//Get the result of a class turned by a JSon.
	BaiduAIFaceStat mBaiduFaceStat;
	// Use this for initialization
	void Start () {	
		token="24.e10414da96e27a71c7dd0ee92eb064ac.2592000.1520400580.282335-10785208";
		//HttpUtility.urlen
		enableMarkDetedted=true;

		enableIdentify=true;
	}
	
	// Update is called once per frame
	void Update () {	
	}



#region for accessing token from url

// Example  access  url  
//https://aip.baidubce.com/oauth/2.0/token?
//		grant_type=client_credentials&
//			client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&
//			client_secret= 0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&


	public IEnumerator getAccessTokenByUnityWWW() {
		WWWForm form = new WWWForm ();
		form.AddField ("grant_type", "client_credentials");
		form.AddField ("client_id", api_key);
		form.AddField ("client_secret", secret_key);		
	
		WWW www = new WWW (token_url, form);
		yield return www;
		Tokenresult = www.text;
		Debug.Log (Tokenresult);	
	}

#endregion





#region  for posting img to Baidu AI and detect
	public IEnumerator PostImageToBaiduAI_detect (byte[] imgBytes)
	{
		enableMarkDetedted=false;
		WWWForm form = new WWWForm ();
		form.AddField ("access_token", token);
		form.AddField ("max_face_num", 10);

		form.AddField ("face_fields", "age,gender,glasses,landmark,landmark72,race");

		//We need base64 format.
	    string format64Str= Convert.ToBase64String(imgBytes);	    

		form.AddField("image",  format64Str);

		WWW www = new WWW (BaiduAI_Face_url_detect, form);
		yield return www;

		BaiduFaceStr=www.text;
	
//		Debug.Log (BaiduFaceStr);	
//		Debug.Log ("     ----------------    ");	
		if(www.text.IndexOf("[")>=0)
		{
			mBaiduFaceStat=ReadFileTool.JsonToClass<BaiduAIFaceStat>(www.text);
			//			if(mBaiduFaceStat!=null)
			//			{
			//				if(mBaiduFaceStat.result_num>0)
			//					foreach(_Result memResult in  mBaiduFaceStat.result  )
			//					{
			//						
			//						Debug.Log ("FaceStat result:  "+"coordx: "+ memResult.landmark[0].x.ToString()
			//							+"   coordY: "+ memResult.landmark[0].y.ToString());	
			//				
			//						Debug.Log ("FaceStat result:  "+"coordx: "+ memResult.landmark72[5].x.ToString()
			//					+"   coordY: "+ memResult.landmark72[5].y.ToString());		
			//					}
			//			}
		}

		enableMarkDetedted=true;
	}
	#endregion


#region  for posting img to Baidu AI and identify his identification among a group
	public IEnumerator PostImageToBaiduAI_identify (byte[] imgBytes, string groupid)
	{
		enableIdentify=false;
		WWWForm form = new WWWForm ();
		form.AddField ("access_token", token);

		form.AddField ("group_id", groupid);

		//We need base64 format.
		string format64Str= Convert.ToBase64String(imgBytes);	    

		form.AddField("image",  format64Str);

		WWW www = new WWW (BaiduAI_Face_url_identify, form);
		yield return www;

		BaiduFaceIdentifyStr=www.text;

		Debug.Log (BaiduFaceIdentifyStr);	
		Debug.Log ("     ----------------    ");	


		enableIdentify=true;
	}
	#endregion


#region  for posting img to Baidu AI Add one more user
	public IEnumerator PostImageToBaiduAI_AddUser (byte[] imgBytes, string groupid,string uid, string userInfo)
	{
		enableAddID=false;

		WWWForm form = new WWWForm ();
		form.AddField ("access_token", token);
		form.AddField ("group_id", groupid);
		form.AddField ("uid", uid);
		form.AddField ("user_info", userInfo);
		//We need base64 format.
		string format64Str= Convert.ToBase64String(imgBytes);	    
		form.AddField("image",  format64Str);

		WWW www = new WWW (BaiduAI_Face_url_AddUserID, form);
		yield return www;

		UserIDResult=www.text;

		Debug.Log (UserIDResult);	
		Debug.Log ("     ----------------    ");	


		enableAddID=true;
	}
	#endregion





	public _Landmark[] GetLandmark4FirstDetectedUser()
	{
		if(mBaiduFaceStat!=null)
		{
			if(mBaiduFaceStat.result_num>0)
				return  mBaiduFaceStat.result[0].landmark;
		}

		return null;
	}



	public _Landmark[] GetLandmark72FirstDetectedUser()
	{
		if(mBaiduFaceStat!=null)
		{
			if(mBaiduFaceStat.result_num>0)
				return  mBaiduFaceStat.result[0].landmark72;
		}

		return null;
	}



	public void LogGender()
	{
		if(mBaiduFaceStat!=null)
		{
			if(mBaiduFaceStat.result_num>0)
				foreach(_Result memResult in  mBaiduFaceStat.result  )
				{
					
					Debug.Log ("Gender:  "+memResult.gender);	
				}
		}
	}

}
